package crons;

import helpers.DateHelper;
import helpers.EmailHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import search.ArticleSearchEngine;
import systems.ConfigSystem;
import systems.Recently;

import models.ArticleModel;
import models.UserModel;
import debugs.ArticleDebug;
import entities.Article;
import entities.ArticleSearch;
import entities.SiteConfig;
import entities.User;

@SuppressWarnings("serial")
public class CronPublishArticle extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		if (siteConfig.getSubmitStatus() == 0) {
		
			ArticleModel articleModel = ArticleModel.getInstance();
			List<Article> articles = articleModel.getArticleUnpublish();
			Article article = null;
			for (int i = 0; i < articles.size(); i++) {
				if (!articles.get(i).isPublished()) {
					article = articleModel.getArticle(articles.get(i).getId());
					if (article != null && !article.isPublished() && !DateHelper.checkGreaterNow(article.getCreated(), 1)) {
						article.setPublished(true);
						article.setStatus(1);
						articleModel.insert(article);
						
						ArticleSearch articleSearch = ArticleSearch.convert(article);
						ArticleSearchEngine.update(articleSearch);
						
						//Update recently Cache
						if (article.isPublished()) {
							Recently.update(article);
							if (article.getLanguage() == "en") {
								postTranslate(article);
							}
						}
						
						//Send email to author
						String serverUrl = UrlHelper.getServerUrl(request);
						String serverName = UrlHelper.getDomainServer(request);
						String strUrl = serverUrl + "/print-email-article-published?id="+article.getId()+"&key=" + article.getAuthKey();
						String strSubject = "[" + serverName + "] Your article has been finish review. You article has been published on " + serverName;
						String emails = article.getEmail() ;
						if (article.getCreator().isEmpty()) {
							UserModel userModel = UserModel.getInstance();
							User user = userModel.getUser(article.getCreator());
							if (user != null) {
								emails = user.getUsername();
							}
						}
						
						SiteConfig config = ConfigSystem.getConfigs();
						EmailHelper.sendMailFromUrl(serverName + " <" + config.getContactEmail() + ">", strSubject, strUrl, emails);
						
						response.getWriter().println("Published article id " + article.getId() + " success.");
					}
				}
			}
		} else {
			response.getWriter().println("Submit config status is " + siteConfig.getSubmitStatus());
		}
	}
	
	private void postTranslate(Article article) {
		String url = "http://eswriterarticle.appspot.com/service/submit-article";
		
		try {
			
			User user = new User();
			UserModel userModel = UserModel.getInstance();
			if (!article.getCreator().isEmpty()) {
				user = userModel.getUser(article.getCreator());
			}
			
			
			String title = article.getTitle();
			String content = article.getContent();
			String category = article.getCategory();
			String name = article.getAuthorName().isEmpty() ? user.getName() : article.getAuthorName();
			String email = article.getEmail().isEmpty() ? user.getUsername() : article.getEmail();
			String website = article.getWebsite().isEmpty() ? user.getWebsite() : article.getWebsite();
			String keywords = article.getTags();
			String sl = "en";
			String tl = "es";
			
			Connection conn = Jsoup.connect(url);
			Document doc = conn
				.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
				.header("accept-Language", "en-us,en;q=0.5")
				//.header("host", "www.webpagetest.org")
				//.header("referer", "http://www.webpagetest.org/")
				//.cookie("o",response.cookie("o"))
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
				.data("title", title)
				.data("content", content)
				.data("category",category)
				.data("name",name)
				.data("email",email)
				.data("website",website)
				.data("keywords",keywords)
				.data("sl", sl)
				.data("tl", tl)
				.followRedirects(false)
				.post();
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}
